<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        const domains = ["https://cdn.topskys.org/v0", "https://cdn.topskys1.org/v1", "https://cdn.topskys2.org/v2"]; // 重试域名数组
        const maxRetry = 3; // 最多重试次数 
        const retryInfo = {}; // 记录重试次数及下一个重试的域名数组下标{times:1,nextIndex:2}
        window.addEventListener("error", e => {
            console.log('出错了', e)
            const tag = e.target
            if (tag.tagName === 'SCRIPT' && !(e instanceof ErrorEvent)) {
                // console.log("JS 加载错误")
                const url = new URL(tag.src) // 拿到script标签的src域名
                if (!retryInfo[url.pathname]) {
                    retryInfo[url.pathname] = {
                        times: 0,
                        nextIndex: 0,
                    }
                }
                const info = retryInfo[url.pathname]; // 取出文件路径 ./loadjs.js ./js.js ./y.js
                const script = document.createElement("script")
                url.host = domains[info.nextIndex]; // 更换域名
                document.write(`<script src="${url.toString()}">\<\/script>`);
                script.src = url.toString();
                document.body.insertBefore(script, tag); // 将新的script标签插入加载错误标签前
                // 修改重试信息
                info.times++;
                info.nextIndex = (info.nextIndex + 1) % domains.length;
            }
        }, true);
    </script>
</head>

<body>
    <script src="https://cdn.topskys.org/v0/js.js"></script>
    <script src="https://cdn.xx1.cn/y.js"></script>
    <script src="https://cdn.xx2.com/loadjs.js"></script>
</body>

</html>